package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.MQ;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.dto.PayOrderDto;
import cn.itsource.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.UnsupportedEncodingException;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "payorderdto-consumer",
        topic = MQ.YMCC_COURSE_ORDER_PAY_TOPIC,
        selectorExpression = MQ.YMCC_COURSE_ORDER_PAY_TAGS
)
public class PayOrderDtoConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt message) {
        try {
            //1.获取消息的字节数组
            byte[] body = message.getBody();
            Assert.isTrue(body != null && body.length > 0, "空消息！");

            //2.转化为字符串
            String jsonString = new String(body, "utf-8");
            log.info("支付服务消费者得到消息：{}", jsonString);

            //3.将json字符串转化为我们需要的实体类对象
            PayOrderDto payOrderDto = JSON.parseObject(jsonString, PayOrderDto.class);

            //4.保存PayOrder
            PayOrder payOrder = new PayOrder();
            BeanUtils.copyProperties(payOrderDto, payOrder);
            log.info("支付服务消费者正在保存支付单：{}", payOrder);
            payOrderService.insert(payOrder);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
